<?php
//ini_set('default_socket_timeout', -1);
/**
 *	@func redis 缓存(百度云版)
 *	@author midoks
 *	@link midoks.cachecha.com
 */
class BaeRedisCache{

	public $cfg = array(
		//'host'=> getenv('HTTP_BAE_ENV_ADDR_REDIS_IP'),
		//'port'=> getenv('HTTP_BAE_ENV_ADDR_REDIS_PORT'),
		//'user'=> getenv('HTTP_BAE_ENV_AK'),
		//'pwd' => getenv('HTTP_BAE_ENV_SK'),
		//'dbname'=> 'ZpRJGkInRvCoHofJvGBF',
		//'database'=> 'local',
	);

	private $link;//连接的资源

	public function __construct(){
		$this->link = new Redis();
		$this->connect();
	}

	public function connect(){
		$this->cfg = array(
			'host'=> getenv('HTTP_BAE_ENV_ADDR_REDIS_IP'),
			'port'=> getenv('HTTP_BAE_ENV_ADDR_REDIS_PORT'),
			'user'=> getenv('HTTP_BAE_ENV_AK'),
			'pwd' => getenv('HTTP_BAE_ENV_SK'),
			'dbname'=> 'ZpRJGkInRvCoHofJvGBF',
          	'char_limit'=> '2048',//value字符长度限制
			//'database'=> 'local',
		);
		$this->link->connect($this->cfg['host'], $this->cfg['port']);//连接BaeRedis
		$this->link->auth($this->cfg['user'].'-'.$this->cfg['pwd'].'-'.$this->cfg['dbname']);//用户认证
	}

	/**
	 *	@func 向redis服务器中,写入值
	 *	@param $key key值
	 *	@param $value value值
	 *	@return 返回
	 */
	public function write($key, $value){
    	if(!$this->link->exists($key)){
      		//var_dump($key, base64_encode(json_encode($value)));
      		//$value = base64_encode(serialize($value));//base64编码
      		$value = wp_db_cache_lzw(serialize($value));//lzw编码(效果比较好)
      		$strlen = strlen($value);
            //var_dump($strlen.'-'.'<br>');
      		if($strlen <= $this->cfg['char_limit']){
      	  		$this->link->setex($key, $this->cfg['timeout'], $value);
			}
		}
        //$this->flush();
	}

	/**
	 *	@func 向redis服务获取值
	 *	@param $key key值
	 */
	public function read($key){
		//获取数据
		$data = $this->link->get($key);
    	//var_dump($data);
		if($data){
			//还原数据
			$data = unserialize(wp_db_cache_unlzw($data));
        	if(!is_array($data)){
           		//var_dump($data);
          		return false;
        	}
      		return $data;
    	}else{
      		return false;
      	}
      	return false;
	}

	/**
	 *	@func 在redis服务器中删除一个元素
	 */
	public function delete($key){
		$this->link->delete($key);
	}

	/**
	 *	@func 清空redis中的所有数据
	 */
	public function flush(){
		$this->link->flushdb();
	}

	//清空过期数据
	public function flush_expire(){
		//会自动销毁
	}
}
?>
